import uuid
from fastapi import UploadFile, File,Form
from fastapi import APIRouter,Body  
import json
import os
from starlette.responses import FileResponse
from typing import List
import os
import time
from moviepy.editor import VideoFileClip,AudioFileClip
import librosa
import numpy as np
import ollama
from json_repair import repair_json
import skvideo.io
import imutils
import re
from typing import Optional
from modelscope.pipelines import pipeline
from modelscope.utils.constant import Tasks
from pydantic import BaseModel
from funasr import AutoModel
import shutil  
import os  
from funasr.utils.postprocess_utils import rich_transcription_postprocess
# asr_pipeline = pipeline(
#     task=Tasks.auto_speech_recognition,
#     model='./iic/SenseVoiceSmall',
#     model_revision="master",
#     device="cuda:0",disable_update=True)


asr_pipeline = pipeline(
    task=Tasks.auto_speech_recognition,
    model='./iic/SenseVoiceSmall',
    model_revision="master",
    device="cuda:0",disable_update=True)

app = APIRouter()

class Message(BaseModel):
    chatId: Optional[str] = ""
    content: Optional[str] = ""
    stream: Optional[bool] = False
    audioHex:  Optional[str] = ""


@app.get('/index')
async def index():
    return {"code":200,"data":{},"msg":"连接服务器成功"}
import uuid
@app.post("/asr")
async def asr(data: Message):  
    # 这里 data 就是接收到的二进制数据  
    # 你可以将其写入文件，或者进行其他处理  
    print(data)
    opusName = "watch/{}".format(uuid.uuid4().hex+".opus")
    pcmName = "watch/{}".format(uuid.uuid4().hex+".pcm")
    wavName = "watch/{}".format(uuid.uuid4().hex+".wav")
    data.audioHex = bytes.fromhex(data.audioHex)  
    with open(opusName, "wb") as f:  
        f.write(data.audioHex)  
    
    os.system('opus_demo  -d 16000 1 {} {}'.format(opusName,pcmName)) 
    os.system('ffmpeg -f s16le -ar 16000 -ac 1 -i {} {}'.format(pcmName,wavName)) 
    
    
    rec_result = asr_pipeline(wavName)
    rec_result = rec_result[0]["text"]
    # rec_result = model.generate(
    #             input="".format(wavName),
    #             cache={},
    #             language="auto",  # "zn", "en", "yue", "ja", "ko", "nospeech"
    #             use_itn=True,
    #             batch_size_s=60,
    #             merge_vad=True,  #
    #             merge_length_s=15,
    #         )
    # rec_result = asr_pipeline("".format(output_file_path))
    psyChat(rec_result)
    print(rec_result)
    return rec_result

@app.post("/chat")
async def chat(data:Message):
    # 这里 data 就是接收到的二进制数据  
    # 你可以将其写入文件，或者进行其他处理  
    # print(data)
    opusName = uuid.uuid4().hex+".opus"
    pcmName = uuid.uuid4().hex+".pcm"
    wavName = uuid.uuid4().hex+".wav"
    data.audioHex = bytes.fromhex(data.audioHex)  
    with open(opusName, "wb") as f:  
        f.write(data.audioHex)  
    
    os.system('opus_demo  -d 16000 1 {} {}'.format(opusName,pcmName)) 
    os.system('ffmpeg -f s16le -ar 16000 -ac 1 -i {} {}'.format(pcmName,wavName)) 
    
    
    rec_result = asr_pipeline(wavName)
    rec_result = rec_result[0]["text"]
    # rec_result = model.generate(
    #             input="".format(wavName),
    #             cache={},
    #             language="auto",  # "zn", "en", "yue", "ja", "ko", "nospeech"
    #             use_itn=True,
    #             batch_size_s=60,
    #             merge_vad=True,  #
    #             merge_length_s=15,
    #         )
    # rec_result = asr_pipeline("".format(output_file_path))
    q = '''
    <我的身体状态>
    {}
    <我的问题，其中包含了我说话的语气情绪如happy angry sad neutral等>
    {}
    '''.format(data.content,rec_result)
    
    reply = psyChat(q)
    print(q)
    print("="*10)
    print(reply)
    return {"code":200,"data":reply,"msg":"成功"}
    
    
def psyChat(question):
    prompt = '''<你的角色和任务>
    你是心理分析专家，能偶洞察我的心理状态。
    若发现我有情绪问题，请用简短的话语和我聊天来对我做心理干预。使得我更加健康。同时好好回答我的问题。
    {}
    '''.format(question)
    
    res=ollama.chat(model="qwen2.5:1.5b",stream=False,messages=[{"role":"system","content":prompt},{"role": "user","content": f"{question}"}],options={"temperature":0})
    
    content = res["message"]["content"]
    return content